//
//  LoginViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginView.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"
#import "PublicLoginApi.h"
#import "PublicGetUserInfoApi.h"
#import "PublicTheThirdLoginApi.h"
#import "PublicSetUserInfoApi.h"
#import "DTCSharePlatformManager.h"
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WeiboSDK.h"

@interface LoginViewController ()

@property(nonatomic,strong) LoginView *containerView;
//@property(nonatomic,strong) RegisterViewController *registerVC;
//@property(nonatomic,strong) ForgetPasswordViewController *forgetVC;


@end

@implementation LoginViewController

#pragma mark - view lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self checkThirdLogin];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.containerView.phoneView.phoneTextField resignFirstResponder];
    [self.containerView.passwordView.passwordTextField resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

// 检查第三方登录是否安装客户端
- (void)checkThirdLogin
{
    if ([QQApiInterface isQQInstalled])
    {
        self.containerView.qqButton.hidden = NO;
    }
    else
    {
        self.containerView.qqButton.hidden = YES;
    }
    
    NSURL * myURL_APP_A = [NSURL URLWithString:@"weixin://"];
    if ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A])
    {
        self.containerView.wechatButton.hidden = NO;
    }
    else
    {
        self.containerView.wechatButton.hidden = YES;
    }
    
    if ([WeiboSDK isCanSSOInWeiboApp])
    {
        self.containerView.weiboButton.hidden = NO;
    }
    else
    {
        self.containerView.weiboButton.hidden = YES;
    }
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    
    [[self.containerView.phoneView.phoneTextField rac_textSignal]subscribeNext:^(id x) {
        NSLog(@"%@",x);
    }];
}

#pragma mark - 点击事件
- (void)didClickRegisterButton
{
    __weak typeof(self) weakSelf = self;
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    vc.registerBlock = ^(NSString *name, NSString *password) {
        weakSelf.containerView.phoneView.phoneTextField.text = name;
        weakSelf.containerView.passwordView.passwordTextField.text = password;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickForgetButton
{
    __weak typeof(self) weakSelf = self;
    ForgetPasswordViewController *vc = [[ForgetPasswordViewController alloc] init];
    vc.forgetBlock = ^(NSString *name, NSString *password) {
        weakSelf.containerView.phoneView.phoneTextField.text = name;
        weakSelf.containerView.passwordView.passwordTextField.text = password;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickLoginButton
{
    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {

        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码.."];
        return;
    }

    if (![self.containerView.passwordView.passwordTextField.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:@"请输入符合规定的密码"];
        return;
    }

//    dispatch_async(dispatch_get_main_queue(), ^{
//        [SVProgressHUD showInfoWithStatus:@"正在登录..."];
//    });
    
    [self loginActionStart];
//    SAVE_OBJECT(@"YES", LOGIN);
}

// 开始登录
- (void)loginActionStart {
    NSString *phone = self.containerView.phoneView.phoneTextField.text;
    NSString *password = self.containerView.passwordView.passwordTextField.text;
    [SVProgressHUD showWithStatus:@"正在登录中..."];
    PublicLoginApi *api = [[PublicLoginApi alloc]initWithDic:@{@"username":phone,@"password":password}];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = [request responseJSONObject];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            EMError *error = [[EMClient sharedClient] loginWithUsername:dict[@"data"][@"uid"] password:password];
            if (!error)
            {
                SAVE_OBJECT(phone , USERNAME);
                SAVE_OBJECT(password, PASSWORD);
                SAVE_OBJECT(dict[@"data"][@"uid"], UID);
                SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
                SAVE_OBJECT(dict[@"data"][@"image"], IMAGE);
                SAVE_OBJECT(@"YES", @"Login");   // 登录状态保存来设置根控制器
                SAVE_OBJECT(@"YES", LOGIN);
                
                [self GetUserInfo];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showSuccessWithStatus:@"您已安全登录！"];
                    [[AppDelegate defaultService] setRootViewController];
                    //设置是否自动登录
                    [[EMClient sharedClient].options setIsAutoLogin:YES];
                    //发送自动登陆状态通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                });
            }
            else
            {
                [SVProgressHUD dismiss];
                switch (error.code)
                {
                    case EMErrorUserNotFound:
                        [SVProgressHUD showErrorWithStatus:@"账号不存在"];
                        break;
                    case EMErrorNetworkUnavailable:
                        [SVProgressHUD showErrorWithStatus:@"没有网络"];
                        break;
                    case EMErrorServerNotReachable:
                        [SVProgressHUD showErrorWithStatus:@"没有网络"];
                        break;
                    case EMErrorUserAuthenticationFailed:
                        [SVProgressHUD showErrorWithStatus:error.errorDescription];
                        break;
                    case EMErrorServerTimeout:
                        [SVProgressHUD showErrorWithStatus:@"连接超时"];
                        break;
                    case EMErrorServerServingForbidden:
                        [SVProgressHUD showErrorWithStatus:@"服务被禁用"];
                        break;
                    case EMErrorUserLoginTooManyDevices:
                        [SVProgressHUD showErrorWithStatus:@"登录设备数已达上限"];
                        break;
                    case EMErrorUserAlreadyLogin:
                    {
                        SAVE_OBJECT(phone , USERNAME);
                        SAVE_OBJECT(password, PASSWORD);
                        SAVE_OBJECT(dict[@"data"][@"uid"], UID);
                        SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
                        SAVE_OBJECT(dict[@"data"][@"image"], IMAGE);
                        SAVE_OBJECT(@"YES", @"Login");   // 登录状态保存来设置根控制器
                        SAVE_OBJECT(@"YES", LOGIN);
                        
                        [self GetUserInfo];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [SVProgressHUD showSuccessWithStatus:@"您已安全登录！"];
                            [[AppDelegate defaultService] setRootViewController];
                            //设置是否自动登录
                            [[EMClient sharedClient].options setIsAutoLogin:YES];
                            //发送自动登陆状态通知
                            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                        });
                    }
                        break;
                    default:
                        [SVProgressHUD showErrorWithStatus:@"登录失败"];
                        break;
                }
            }
        });
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:[request responseJSONObject][@"errmsg"]];
    }];

    
//    [SVProgressHUD showInfoWithStatus:@"正在登录中..."];


}





- (void)didClickQQButton
{
    [DTCSharePlatformManager qqLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.uid andType:@"1" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)didClickWechatButton
{
    [DTCSharePlatformManager wechartLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.rawData[@"unionid"] andType:@"2" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)didClickWeiboButton
{
    [DTCSharePlatformManager weiboLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.uid andType:@"3" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)theThirdLoginWithOpenId:(NSString *)openid andType:(NSString *)loginType andModifyInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon
{
    
    PublicTheThirdLoginApi *loginApi = [[PublicTheThirdLoginApi alloc]initWithDic:@{@"openid":openid,@"type":loginType}];
    [loginApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        //保存数据
        NSDictionary * dict = [loginApi responseJSONObject];
        NSLog(@"dict = %@",dict[@"errmsg"]);
        if ([dict[@"errcode"] intValue] == 0) {
            SAVE_OBJECT(dict[@"data"][@"uid"], UID);
            SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
            //            NSLog(@"login = %@",EXRACT_OBJECT(LOGINING));
            if ([dict[@"data"][@"is_first_login"] boolValue]) // 第一次第三方登录需要注册环信
            {
                [self chatRegisterWithUID:dict[@"data"][@"uid"] UserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:[dict[@"data"][@"is_first_login"] boolValue]];
            }
            else
            {
                [self chatLoginWithUID:dict[@"data"][@"uid"] UserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:[dict[@"data"][@"is_first_login"] boolValue]];
            }
//            [self modifyUserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:[dict[@"data"][@"is_first_login"] boolValue] uid:dict[@"data"][@"uid"]];
//            NSLog(@"第三方第一次登陆标志：%@",dict[@"data"][@"is_first_login"]);
            
        } else {
            [SVProgressHUD showErrorWithStatus:dict[@"errmsg"]];
        }
        
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@",request.error);
        [SVProgressHUD showErrorWithStatus:@"登陆失败！"];
    }];
}

//修改用户信息
- (void)modifyUserInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon andFirst:(BOOL)first uid:(NSString *)uid
{
    if (first) {
        UIImageView *imageView = [[UIImageView alloc]init];
        [[AppDelegate defaultService].window addSubview:imageView];
        imageView.hidden = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:icon] completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, NSURL *imageURL) {
            [UIImageJPEGRepresentation(image, 0.5f) writeToFile:PorPath atomically:YES];
            
            PublicSetUserInfoApi *modifyApi = [[PublicSetUserInfoApi alloc]initWithDic:@{@"nickname":nickname,@"sex":sex,@"image":PorPath}];
            [modifyApi dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                NSDictionary *dic = [modifyApi responseJSONObject];
                NSLog(@"errcode dic = %@",dic[@"errmsg"]);
                if([dic[@"errcode"] intValue] == 0) {
                    [SVProgressHUD showSuccessWithStatus:@"用户登陆成功"];
                    SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
                    SAVE_OBJECT(sex, SEX);
                    SAVE_OBJECT(nickname, NICKNAME);
                    SAVE_OBJECT(icon, IMAGE);
                    [SVProgressHUD dismiss];
                    //跳转主页
                    [[AppDelegate defaultService] setRootViewController];
                } else {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                }
            } failure:nil];

        }];
        

    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            SAVE_OBJECT(icon, IMAGE);
            SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
            [[AppDelegate defaultService]setRootViewController];
        });
    }
}

// 第三方登录后调环信登录
- (void)chatLoginWithUID:(NSString *)uid UserInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon andFirst:(BOOL)first
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:uid password:@"123456"];
        if (!error)
        {
            //修改用户信息
            [self modifyUserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:first uid:uid];
        }
        else
        {
            [SVProgressHUD dismiss];
            switch (error.code) {
                case EMErrorServerNotReachable:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                    break;
                case EMErrorUserAlreadyExist:
                    TTAlertNoTitle(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
                    break;
                case EMErrorNetworkUnavailable:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                    break;
                case EMErrorServerTimeout:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                    break;
                case EMErrorServerServingForbidden:
                    TTAlertNoTitle(NSLocalizedString(@"servingIsBanned", @"Serving is banned"));
                    break;
                default:
                    TTAlertNoTitle(NSLocalizedString(@"register.fail", @"Registration failed"));
                    break;
            }
        }
    });
}

// // 第三方登录后调环信注册
- (void)chatRegisterWithUID:(NSString *)uid UserInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon andFirst:(BOOL)first
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] registerWithUsername:uid password:@"123456"];
        if (!error)
        {
            //修改用户信息
            [self modifyUserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:first uid:uid];
        }
        else
        {
            [SVProgressHUD dismiss];
            switch (error.code) {
                case EMErrorServerNotReachable:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                    break;
                case EMErrorUserAlreadyExist:
                    TTAlertNoTitle(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
                    break;
                case EMErrorNetworkUnavailable:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                    break;
                case EMErrorServerTimeout:
                    TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                    break;
                case EMErrorServerServingForbidden:
                    TTAlertNoTitle(NSLocalizedString(@"servingIsBanned", @"Serving is banned"));
                    break;
                default:
                    TTAlertNoTitle(NSLocalizedString(@"register.fail", @"Registration failed"));
                    break;
            }
        }
    });

}

#pragma mark - 事件处理
- (void)GetUserInfo {
    
    PublicGetUserInfoApi * userInfoApi = [[PublicGetUserInfoApi alloc] init];
    [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [userInfoApi analyseResponseObject];
        SAVE_OBJECT(@"YES", LOGIN);
        [[AppDelegate defaultService]setRootViewController];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"获取用户信息失败！"];
    }];
}

#pragma mark - 代理


#pragma mark - 通知处理

#pragma mark - 初始化


- (LoginView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[LoginView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.registerButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.forgetButton addTarget:self action:@selector(didClickForgetButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.loginButton addTarget:self action:@selector(didClickLoginButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.qqButton addTarget:self action:@selector(didClickQQButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.wechatButton addTarget:self action:@selector(didClickWechatButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.weiboButton addTarget:self action:@selector(didClickWeiboButton) forControlEvents:UIControlEventTouchUpInside];

    }
    return _containerView;
}


- (void)setNavigationStyle
{
    [self setLeftButtonImage:nil];
    
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
}


@end
